//
//  UIWgtMeasType.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/10/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>

#import "AppDelegate.h"
#import "UIBodyProfileViewCtrl.h"

#import "UIWgtMeasType.h"

@implementation UIWgtMeasType {
    UIButton* _btnWiFiType;
    UIButton* _btnBleType;
    UIButton* _btnBcaType;
    UIButton* _btnManual;
    
    id _wtDelegate;
    short _nWgtTypeIdx;
    
    //QR code scan
    BOOL _bQrReading;
    UIView* _viewQRcode;
    AVCaptureSession* _cptQRSession;
    AVCaptureVideoPreviewLayer* _cvpQRLayer;
    
    NSString* _ScanRQCode;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //UIColor* colBkgd = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"ic-bottbkgd-t.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        //self.backgroundColor = colBkgd;
        
        //_nSelBtn = -1;
        [self initialize: frame];
    }
    self.backgroundColor = [UIColor colorWithWhite:0.125 alpha:0.85];
    //self.backgroundColor = [UIColor colorWithRed:0.123 green:0.123 blue:0.123 alpha:0.720];
    
    _nWgtTypeIdx = -1;
    
     _bQrReading = NO;
    _viewQRcode = nil;
    _cptQRSession = nil;
    _cvpQRLayer = nil;
    
    _ScanRQCode = @"";
    
    return self;
}

- (void) initialize:(CGRect)frame
{
    //BOOL bIpad = frame.size.width > 700;
    CGRect rt = CGRectMake(0, 0, frame.size.width, frame.size.height);
    CGFloat xMargin = 24.0;//frame.size.width / 20.0;
    CGFloat yMargin = 24.0;//frame.size.height / 20.0;
    
    rt.origin.x = xMargin;
    rt.origin.y = yMargin;
    rt.size.width = frame.size.width / 2.0 - xMargin * 2.0;
    rt.size.height = frame.size.height / 2.0 - yMargin * 2.0;
    
    UIImage* iCon = [[UIImage imageNamed:@"btn-wgtwifi.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _btnWiFiType = [[UIButton alloc] initWithFrame:rt];
    [_btnWiFiType setImage:iCon forState:UIControlStateNormal];
    //[_btnWiFiType[1] setBackgroundImage:[UIImage imageNamed:@"ic-uarrow_sel.png"] forState:UIControlStateSelected];
    [_btnWiFiType addTarget:self action:@selector(tapWgtMeasButs:) forControlEvents:UIControlEventTouchUpInside];
    //[self addSubview:_btnWiFiType];
    
    iCon = [[UIImage imageNamed:@"btn-wgtble.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    rt.origin.x += frame.size.width / 2.0;
    _btnBleType = [[UIButton alloc] initWithFrame:rt];
    [_btnBleType setImage:iCon forState:UIControlStateNormal];
    [_btnBleType addTarget:self action:@selector(tapWgtMeasButs:) forControlEvents:UIControlEventTouchUpInside];
    //[self addSubview:_btnBleType];
    
    
    //iCon = [[UIImage imageNamed:@"btn-wgtbca.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    iCon = [[UIImage imageNamed:@"btn-wgtwifi_s.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    rt.origin.x -= frame.size.width / 2.0;
    rt.origin.y += frame.size.width / 2.0;
    _btnBcaType = [[UIButton alloc] initWithFrame:rt];
    [_btnBcaType setImage:iCon forState:UIControlStateNormal];
    [_btnBcaType addTarget:self action:@selector(tapWgtMeasButs:) forControlEvents:UIControlEventTouchUpInside];
    //[self addSubview:_btnBcaType];
    
    iCon = [[UIImage imageNamed:@"btn-wgtmul.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    rt.origin.x += frame.size.width / 2.0;
    _btnManual = [[UIButton alloc] initWithFrame:rt];
    [_btnManual setImage:iCon forState:UIControlStateNormal];
    [_btnManual addTarget:self action:@selector(tapWgtMeasButs:) forControlEvents:UIControlEventTouchUpInside];
    // [self addSubview:_btnManual];
    
}

- (void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGFloat rd = 15.0;
    CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect);
    CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy = CGRectGetMaxY(rect);
    
    if(_cptQRSession == nil)
      CGContextSetRGBStrokeColor(ctx, 0.0/255, 140.0/255, 189.0/255, 0.75);
    else
      CGContextSetRGBStrokeColor(ctx, 1.0, 1.0, 1.0, 0.95);
    CGContextSetLineWidth(ctx, 2.75);
    //drae rect
    CGContextMoveToPoint(ctx, minx, midy);
    // Add an arc through 2 to 3
    CGContextAddArcToPoint(ctx, minx, miny, midx, miny, rd);
    // Add an arc through 4 to 5
    CGContextAddArcToPoint(ctx, maxx, miny, maxx, midy, rd);
    // Add an arc through 6 to 7
    CGContextAddArcToPoint(ctx, maxx, maxy, midx, maxy, rd);
    // Add an arc through 8 to 9
    CGContextAddArcToPoint(ctx, minx, maxy, minx, midy, rd);
    // Close the path
    CGContextClosePath(ctx);
    // Fill & stroke the path
    CGContextDrawPath(ctx, kCGPathStroke);
  
  //draw blue line
  CGContextSetRGBStrokeColor(ctx, 0.0/255, 140.0/255, 189.0/255, 0.75);
  CGContextSetLineWidth(ctx, 3.5);
  
  CGRect rt = self.frame;
  CGFloat xPos1 = 20;
  CGFloat yPos1 = rt.size.width / 2;
  CGFloat xPos2 = rt.size.width / 2 - xPos1;
  CGFloat yPos2 = rt.size.width / 2;
  CGContextMoveToPoint(ctx, xPos1, yPos1);
  CGContextAddLineToPoint(ctx, xPos2, yPos2);
  
  xPos1 += rt.size.width / 2;
  xPos2 += rt.size.width / 2;
  CGContextMoveToPoint(ctx, xPos1, yPos1);
  CGContextAddLineToPoint(ctx, xPos2, yPos2);
  
  xPos1 = rt.size.width / 2;
  yPos1 = rt.size.width / 2 - 20;
  xPos2 = rt.size.width / 2;
  yPos2 = 20;
  CGContextMoveToPoint(ctx, xPos1, yPos1);
  CGContextAddLineToPoint(ctx, xPos2, yPos2);
  
  yPos1 = rt.size.width / 2 + 20;
  yPos2 = rt.size.width - 20;
  CGContextMoveToPoint(ctx, xPos1, yPos1);
  CGContextAddLineToPoint(ctx, xPos2, yPos2);
  
  CGContextStrokePath(ctx);
  //UIGrapCGContextClosePathhicsEndImageContext();
}

- (void) addWgtTypeButs
{
    if(_btnWiFiType == nil)
        return;
    
    [self addSubview:_btnWiFiType];
    [self addSubview:_btnBleType];
    [self addSubview:_btnBcaType];
    [self addSubview:_btnManual];
}

- (void) rmvWgtTypeButs
{
    /*[_btnWiFiType removeFromSuperview];
    [_btnBleType removeFromSuperview];
    [_btnBcaType removeFromSuperview];
    [_btnManual removeFromSuperview];*/
    NSArray *vToRemove = [self subviews];
    for (UIView *v in vToRemove) {
        [v removeFromSuperview];
    }
    
    if(_cptQRSession != nil) {
        [self stopQRReading];
    }
    self.backgroundColor = [UIColor colorWithWhite:0.128 alpha:0.98];
    _bQrReading = NO;
}

- (void) tapWgtMeasButs:(id) sender
{
    short nIdx = -1;
    if(sender == _btnWiFiType) {
        nIdx = 0;
        //AudioServicesPlaySystemSound(1115);
    }
    else if(sender == _btnBleType) {
        nIdx = 1;
        //AudioServicesPlaySystemSound(1315);
    }
    else if(sender == _btnBcaType) {
        nIdx = 2;
        //AudioServicesPlaySystemSound(1100);
    }
    else {
        nIdx = 3;
        //AudioServicesPlaySystemSound(1109);
    }
    _nWgtTypeIdx = nIdx;
    
    [self rmvWgtTypeButs];
    [self wgtDevTypeSel];
}

-(void) wgtDevTypeSel
{
  if(_nWgtTypeIdx == 0/* || _nWgtTypeIdx == 2*/) { //wifi & bca
    [self setQRcodeScanUI];
  }
  if (_wtDelegate && [_wtDelegate respondsToSelector:@selector(onWgtTypeChged:)]) {
    [_wtDelegate onWgtTypeChged:_nWgtTypeIdx];
  }
}

- (void) setQRcodeScanUI
{
    CGRect rt = self.frame;
    self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.95];
    
    UIImageView *ivQr1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic-qrfrm-1.png"]];
    ivQr1.frame = CGRectMake(0, 0, 64, 64);
    [self addSubview:ivQr1];
    
    UIImageView *ivQr2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic-qrfrm-2.png"]];
    ivQr2.frame = CGRectMake(rt.size.width-64, 1, 64, 64);
    [self addSubview:ivQr2];
    
    UIImageView *ivQr3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic-qrfrm-3.png"]];
    ivQr3.frame = CGRectMake(1, rt.size.height-64, 64, 64);
    [self addSubview:ivQr3];
    
    UIImageView *ivQr4 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic-qrfrm-4.png"]];
    ivQr4.frame = CGRectMake(rt.size.width-64, rt.size.height-64, 64, 64);
    [self addSubview:ivQr4];
    
    _bQrReading = NO;
    
    //[self performSelectorInBackground:@selector(startConnActindicator) withObject:nil];
    /*AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _bHostConn = [_socketSvr isConnNetwork];
    if(!_bHostConn) {
        [pApp CloseScaleHost];
        _bHostConn = [appDelegate ConnScaleHost:YES IpAddr: NULL Port:_Host_Port];
    }
    [self performSelectorInBackground:@selector(stopConnActindicator) withObject:nil];
    if(_bHostConn) {
        _socketSvr = appDelegate.socketHost;
        _socketSvr.svrDelegate = self;
    }
    else {
        _btnRfid.hidden = NO;
        _lblState.text = NSLocalizedString(@"NoCloudConn", nil);
        AudioServicesPlaySystemSound(1112);
        return;
    }*/
    BOOL bIos64Bit = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0;
    if(bIos64Bit/* && _bHostConn*/) {
        //if(_viewQRcode == nil)
            [self startStopReading];
        //else
            //[self startQRReading];
        
        //_bHostConnData = YES;
        //[self sendCardNoToHost];
        
        AudioServicesPlaySystemSound(1109);
    }
    else {
        //_lblState.text = @"Need iOS7 or Higher version!";
        AudioServicesPlaySystemSound(1112);
    }
    [self setNeedsDisplay];
}

#pragma mark -QR code scan
- (BOOL)startQRReading {
    NSError *error;
    
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    _cptQRSession = [[AVCaptureSession alloc] init];
    [_cptQRSession addInput:input];
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_cptQRSession addOutput:captureMetadataOutput];
    
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    _cvpQRLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_cptQRSession];
    [_cvpQRLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_cvpQRLayer setFrame:_viewQRcode.layer.bounds];
    [_viewQRcode.layer addSublayer:_cvpQRLayer];
    
    [_cptQRSession startRunning];
    
    return YES;
}

-(void)stopQRReading {
    if(_cptQRSession == nil)
        return;
    
    [_cptQRSession stopRunning];
    _cptQRSession = nil;
    
    [_cvpQRLayer removeFromSuperlayer];
    
    _viewQRcode.hidden = YES;
    //_btnRfid.hidden = NO;
    //_lblState.text = NSLocalizedString(@"WaitComm", nil);
}

- (void)startStopReading
{
    if(_viewQRcode == nil) {
        //eWgtAppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
        //CGFloat W = appDelegate.viewWidth;
        //CGFloat H = appDelegate.viewHeight;
        //CGFloat fSize = (H  > 1000)? 300: 160;
        CGFloat xPos = 16;
        CGFloat yPos = 16;
        CGFloat fSize = self.frame.size.width - xPos - yPos;
        
        CGRect rt;
        rt.origin.x = xPos;
        rt.origin.y = yPos;
        
        
        rt.size.height = fSize;
        rt.size.width = fSize;
        _viewQRcode = [[UIView alloc] initWithFrame:rt];
        _viewQRcode.layer.masksToBounds = YES;
        _viewQRcode.layer.cornerRadius = 4;
    }
    [self addSubview:_viewQRcode];
    _viewQRcode.hidden = NO;
    if (!_bQrReading) {
        if ([self startQRReading]) {
            //_lblState.text =  NSLocalizedString(@"WgQrTip", nil);//@"Scanning QR Code on Scale...";
            //_lblState.textColor = [UIColor redColor];
            //_lblConn.text = @"Scan It...";
        }
        //_bSendTagDevInfo = NO;
        //_ScanRQCode = @"********";
    }
    else{
        [self stopQRReading];
        /*_lblConn.text = @"Stop";
        
        [self closeTagIdSocket:_UserCardNo];
        _socketSvr.svrDelegate = nil;
        [_socketSvr turnConnOff];*/
    }
    
    _bQrReading = !_bQrReading;
    //_btnChgUser.hidden = _bQrReading;
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            //m_bResolved = YES;
            _ScanRQCode = [metadataObj stringValue];
            //[self sendCardNoToScale:NO dev:_ScanRQCode]; viewctrk di that
            
            if(!_bQrReading)
                return;
            
            //stop QR func
            [self performSelectorOnMainThread:@selector(stopQRReading) withObject:nil waitUntilDone:NO];
            [self performSelectorOnMainThread:@selector(scanQRcodeCompleted) withObject:nil waitUntilDone:NO];
            //[self performSelectorInBackground:@selector(scanQRcodeCompleted) withObject:nil];
            
            //[_lblConn performSelectorOnMainThread:@selector(setText:) withObject:sQrCode waitUntilDone:NO];
            //_bFatWatScale = [sQrCode hasPrefix:@"BFS"];
            //_lblConn.text = ;
            
            //[self rmvWgtTypeButs];
            AudioServicesPlaySystemSound(1115);
            _bQrReading = NO;
        }
    }
}

- (void) scanQRcodeCompleted
{
    if (_wtDelegate && [_wtDelegate respondsToSelector:@selector(ScanedQRcode:)]) {
        [_wtDelegate ScanedQRcode:_ScanRQCode];
    }
}
#pragma mark -QR code end

@end
